<?php

namespace PKApp\Content\Classes;

use PKFrame\DataHandler\Arrays;
use PKFrame\Lib\DataBase;

class ContentDataBase extends DataBase
{
    protected $tableData;

    public function __construct($table)
    {
        parent::__construct();
        $table = strtolower($table);
        $this->table = $table;
        $this->tableData = $table . '_data';
    }

    public function GetListByCatSort(array $viewParams, int $rows = 0, int $index = 0)
    {
        $catIds = $where = '';
        foreach ($viewParams as $key => $item) {
            switch ($key) {
                case 'catId':
                    $catIds = implode(',', $viewParams['catId']);
                    break;
                case 'toHead':
                case 'toPush':
                case 'toTop':
                    $where = ' AND '.$key.' = 1';
                    break;
            }
        }
        $index = ($index - 1) * $rows;
        $this->sql[] = <<<SQL
SELECT C.*
 FROM `pk_{$this->table}` AS C, `pk_category` AS Cat
  WHERE C.`catId` = Cat.`id` AND C.`isDeleted` = 0 AND Cat.`isDeleted` = 0 AND C.`catId` IN ({$catIds}){$where}
  ORDER BY Cat.`listSort` ASC, Cat.`id` DESC, C.`id`DESC
  LIMIT {$index},{$rows}
SQL;
        return $this->ToList();
    }

    public function GetListByData($id_list)
    {
        $table_data = $this->getTableName($this->tableData);
        $id_str = implode(',', $id_list);
        $this->sql[] = <<<SQL
SELECT * FROM {$table_data} WHERE id IN ({$id_str})
SQL;
        return $this->ToList();
    }

    public function CopyToOtherCategoryByDataList($data)
    {
        $this->Insert($data, $this->tableData, true)->BatchRun();
    }

    public function GetDetail($option = [], $field = '*')
    {
        $this->join($this->tableData, 'id');
        if (Arrays::Is($option)) {
            foreach ($option as $key => $value) {
                $this->WhereJoin($key, $value);
            }
        }
        return $this->Select($field)->First();
    }

    public function TruncateByContent()
    {
        $this->Truncate()->Truncate($this->tableData)->BatchRun();
    }

    public function GetDetailByPageIndex($index, $params_where = [])
    {
        array_key_exists('isDeleted', $params_where) ?: $params_where['isDeleted'] = 0;
        $this->join($this->tableData, 'id');
        return $this->Where($params_where)
            ->OrderBy('id', 'ASC')->Limit(1, $index)->Select()->First();
    }

    public function SaveData($params, $id = 0): ?int
    {
        if ($id == 0) {
            $id = $this->Insert($params['base'])->Exec();
            $this->Insert(array_merge($params['data'], ['id' => $id]), $this->tableData)->Exec();
        } else {
            $this->Where(['id' => $id])->Update($params['base'])->Exec();
            if (Arrays::Is($params['data'])) {
                $this->Where(['id' => $id])->Update($params['data'], $this->tableData)->Exec();
            }
        }
        return $id;
    }

    // 内容页面 取内容的上下文
    public function GetContentUpOrNext($viewParams, $order_field, $order_mode)
    {
        $where = ['isDeleted' => 0];
        !Arrays::Is($viewParams) ?: $where = array_merge($where, $viewParams);
        $this->Where($where);
        $this->sql[] = <<<SQL
SELECT id,title,url FROM {$this->getTableName()} WHERE id IN (
    SELECT id FROM {$this->getTableName()} {$this->GetWhere()} {$this->GetOrder()}
    ) ORDER BY {$order_field} {$order_mode} limit 1; 
SQL;
        return $this->First();
    }

    public function ReplaceFieldContent(string $replace_str, bool $is_list)
    {
        if ($is_list) {
            $this->sql[] = <<<SQL
update `pk_{$this->table}` set {$replace_str};
SQL;
        } else {
            $this->sql[] = <<<SQL
update `pk_{$this->tableData}` set {$replace_str};
SQL;
        }
        $this->Exec();
    }

}